package com.dst.filter;

import com.dst.utli.JwtUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebSession;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
public class MyFilter implements GlobalFilter, Ordered {

  @Override
  public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    String uri = exchange.getRequest().getURI().toString();
    if(uri.indexOf("/user-test/")>-1){
      return chain.filter(exchange);
    }
    List<String> authorization = exchange.getRequest().getHeaders().get("authorization");
    if(authorization!=null&authorization.size()>0){
      String token = authorization.get(0);
      try {
        JwtUtils.verify(token);
        return chain.filter(exchange);
      } catch (Exception e) {
        exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
        return exchange.getResponse().setComplete();
      }
    }
      exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
      return exchange.getResponse().setComplete();

  }

  @Override
  public int getOrder() {
    return 0;
  }
}
